package model;

import org.junit.jupiter.api.Test;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;
import weka.classifiers.functions.SMOreg;
import weka.classifiers.Evaluation;

import java.util.ArrayList;

public class ModelTrainingTest {

    @Test
    public void trainAndEvaluateModel() throws Exception {
        // 创建属性
        ArrayList<Attribute> attributes = new ArrayList<>();
        attributes.add(new Attribute("bbl"));
        attributes.add(new Attribute("number"));
        attributes.add(new Attribute("methodNumeric")); // 将方法作为数值属性
        attributes.add(new Attribute("line"));

        // 创建Instances对象
        Instances dataset = new Instances("UniversityData", attributes, 0);
        dataset.setClassIndex(dataset.numAttributes() - 1); // 设置line为目标变量

        // 添加数据
        dataset.add(new DenseInstance(1.0, new double[]{0.14, 28, 1, 260}));
        dataset.add(new DenseInstance(1.0, new double[]{0.45, 22, 1, 264}));
        dataset.add(new DenseInstance(1.0, new double[]{0.63, 19, 1, 263}));
        dataset.add(new DenseInstance(1.0, new double[]{1.09, 23, 1, 273}));
        dataset.add(new DenseInstance(1.0, new double[]{0.78, 19, 1, 273}));

        // 实施网格搜索
        double[] C_values = {0.1, 0.5, 1.0, 2.0};
        double bestC = 0;
        double bestMSE = Double.MAX_VALUE;
        SMOreg bestModel = null;

        for (double C_value : C_values) {
            SMOreg smoreg = new SMOreg();
            smoreg.setC(C_value);
            smoreg.buildClassifier(dataset);

            // 对于小数据集，使用较小的折数
            int folds = dataset.numInstances() < 10 ? dataset.numInstances() : 10;

            Evaluation eval = new Evaluation(dataset);
            eval.crossValidateModel(smoreg, dataset, folds, new java.util.Random(1));

            double mse = eval.rootMeanSquaredError();
            if (mse < bestMSE) {
                bestMSE = mse;
                bestC = C_value;
                bestModel = smoreg;
            }
        }

        // 输出模型评估结果
        System.out.println("Best C: " + bestC);
        System.out.println("Best MSE: " + bestMSE);
    }
}



